import React, { useState, useEffect } from 'react';
import { Button } from 'antd';
import { useHistory } from 'react-router-dom';
import {
  openNotification_util, checkdatavalid_util_formdata, fetchsync_util,
  resultdata_to_formdata, 
  use_dict_byzdmc,
  use_olreport_bybbbm,
  convertISODateTimeToYYYYMMDD,
} from '../util/util.js'
import Customfielditem_hook from '../newmes/customfielditem_hook.js'
import moment from 'moment'
import 'moment/locale/zh-cn'
import {use_gyspj_initformdata,use_gyspj_initformdata_view} from './use_gyszx_config.js';
moment.locale('zh-cn')
var storage = window.localStorage;
import useStore from '../../useStore.js'
import { dropByCacheKey } from 'react-router-cache-route'


const Gyspj_form = () => {
  const history = useHistory();
  //动态数据源
  const [dynDatasObject, setdynDatasObject] = useState({
    query_gys:[]
  })
  const [isloading, setisloading] = useState(true)

  /**
   * 强制刷新明细表 用于特殊场景
   */
  const [switche, setswitche] = useState(true);
  const forceupdate = () => { setswitche(false) }
  useEffect(() => { switche ? "1" : setswitche(true) }, [switche])

  const init = async () => {
    setisloading(true)
    var bbObj = await use_olreport_bybbbm(["data_ejfl","query_gys"])
    
    dynDatasObject.query_gys = bbObj.query_gys

    setdynDatasObject({ ...dynDatasObject })
    setisloading(false)
  }

  //主表数据
  const [formdata, setformdata] = useState(JSON.parse(storage.pre_gyspj_item).type=="view"?use_gyspj_initformdata_view:use_gyspj_initformdata)
  const { nowroute, setnowroute, collapsed, setcollapsed } = useStore();


  //加载主表数据
  const loadformdata = async (id) => {
    let rtdata = await fetchsync_util("/admin/gyszx/query_gyskp_byid", 'POST', { id }, "json")
    rtdata.resultdata.formdata.kpzqq = rtdata.resultdata.formdata.kpzqq ? convertISODateTimeToYYYYMMDD(rtdata.resultdata.formdata.kpzqq) : ""
    rtdata.resultdata.formdata.kpzqz = rtdata.resultdata.formdata.kpzqz ? convertISODateTimeToYYYYMMDD(rtdata.resultdata.formdata.kpzqz) : ""
    setformdata({ ...formdata, ...resultdata_to_formdata(rtdata.resultdata.formdata, formdata) });
  }


  // 页面进入加载数据
  useEffect(() => {
    if(JSON.parse(storage.pre_gyspj_item).type != "add"){
      loadformdata(JSON.parse(storage.pre_gyspj_item).data.id)
    }
    init()
  }, [])
  // 监听各评分字段变化,计算总分并设置等级
  const handleFormdataChange = ()=>{
    let newformdata = {...formdata}
    console.log(newformdata.jyhgps.value*1,newformdata.zjlps.value*1,newformdata.asjhps.value*1 / newformdata.zjlps_jf.value*1);
    //计算批次合格率
    if(!isNaN((newformdata.jyhgps.value*1 / newformdata.zjlps.value*1)) && newformdata.zjlps.value*1 != 0){
      newformdata.pchgl.value = (newformdata.jyhgps.value / newformdata.zjlps.value).toFixed(2) * 100 + "%"
    }
    //计算按时交货率
    if(!isNaN((newformdata.asjhps.value*1 / newformdata.zjlps_jf.value*1)) && newformdata.zjlps_jf.value*1 != 0){
      newformdata.asjhl.value = (newformdata.asjhps.value / newformdata.zjlps_jf.value).toFixed(2) * 100 + "%"
    }
    newformdata.zdf.value = newformdata.zldf.value*1 + newformdata.jfdf.value*1 + newformdata.jgdf.value*1 + newformdata.fwdf.value*1 
    
    // 实时验证评分字段
    validateScoreFields(newformdata);
    
    setformdata(newformdata)
  }

  // 验证评分字段的函数
  const validateScoreFields = (formData) => {
    const validationMessages = [];
    
    // 验证质量得分不大于40
    if (formData.zldf.value && parseFloat(formData.zldf.value) > 40) {
      validationMessages.push("质量得分不能大于40分");
    }
    
    // 验证交付得分不大于40
    if (formData.jfdf.value && parseFloat(formData.jfdf.value) > 40) {
      validationMessages.push("交付得分不能大于40分");
    }
    
    // 验证价格得分不大于15
    if (formData.jgdf.value && parseFloat(formData.jgdf.value) > 15) {
      validationMessages.push("价格得分不能大于15分");
    }
    
    // 验证服务得分不大于15
    if (formData.fwdf.value && parseFloat(formData.fwdf.value) > 15) {
      validationMessages.push("服务得分不能大于15分");
    }
    
    // 如果有验证错误，显示警告信息（但不阻止继续操作）
    if (validationMessages.length > 0) {
      console.warn("评分验证警告：", validationMessages.join("；"));
    }
  }

  //设置value
  const setfield = (onekey, value, settype) => {
    if (settype == 'single') {
      var newitem = formdata[onekey]
      newitem.value = value
      let newformdata = Object.assign({}, formdata, { [onekey]: newitem });
      setformdata(newformdata)
    }
    else if (settype == "muti") {
      let [tansferarr, selectrow, newformdata] = [onekey, value, {}];
      tansferarr.forEach(item => {
        var newitem = formdata[item.target]
        newitem.value = selectrow ? selectrow[item.origin] : ""
        newformdata = Object.assign({}, formdata, { [item.target]: newitem });
      })
      setformdata(newformdata)
    }

  }

  const handleback = () => {
    dropByCacheKey('gyspj_list')
    dropByCacheKey('gyspj_form')
    setnowroute({ route: "/shipSRM/gyszx/gyspj_list", title: "供应商评价", closeroute: "/shipSRM/gyszx/gyspj_form" })
  }

  const handleupload = async () => {
    // 评分字段验证
    const validationErrors = [];
    
    // 验证质量得分不大于40
    if (formdata.zldf.value && parseFloat(formdata.zldf.value) > 40) {
      validationErrors.push("质量得分不能大于40分");
    }
    
    // 验证交付得分不大于40
    if (formdata.jfdf.value && parseFloat(formdata.jfdf.value) > 40) {
      validationErrors.push("交付得分不能大于40分");
    }
    
    // 验证价格得分不大于15
    if (formdata.jgdf.value && parseFloat(formdata.jgdf.value) > 15) {
      validationErrors.push("价格得分不能大于15分");
    }
    
    // 验证服务得分不大于15
    if (formdata.fwdf.value && parseFloat(formdata.fwdf.value) > 15) {
      validationErrors.push("服务得分不能大于15分");
    }
    
    // 如果有验证错误，显示错误信息并返回
    if (validationErrors.length > 0) {
      openNotification_util(validationErrors.join("；"));
      return;
    }

    var checkobj = checkdatavalid_util_formdata(formdata)
    //主表字段校验没通过不能保存，目前没写子表校验。

    if (!checkobj.rtstatus) { openNotification_util(checkobj.rtmessage); return; }
    else;


    //设置submit url
    var uploadurl = "/admin/gyszx/add_gyskp";
    let rtdata = await fetchsync_util(uploadurl, 'POST', {
      formdata,
    }, "json")
    rtdata.rtstatus ? openNotification_util(rtdata.rtmessage) : 1
    setformdata(rtdata.resultdata.formdata);
    dropByCacheKey('gyspj_list')
    dropByCacheKey('gyspj_form')
    setnowroute({ route: "/shipSRM/gyszx/gyspj_list", title: "供应商评价", closeroute: "/shipSRM/gyszx/gyspj_form" })
  }


  const renderfileditem = () => {
    var formdataarr = []
    for (var formitemkey in formdata) {
      formdata[formitemkey].inputType == "none" ? "" : formdataarr.push(formdata[formitemkey])
    }
    var renderstr = formdataarr.map(item => {
      var rtitem = item.input_type == "space_item" ?
        <Customfielditem_hook form={formdata} item={{ inputType: "none" }}
          handlechange={(key, value, settype) => { setfield(key, value, settype);handleFormdataChange() }} />
        :
        <Customfielditem_hook form={formdata} item={formdata[item.dataIndex]}
          dynDatasObject={dynDatasObject}
          handlechange={(key, value, settype) => { setfield(key, value, settype);handleFormdataChange() }} />
      return rtitem
    }
    )
    return renderstr
  }

  return (

    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "5.9vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem"
    }}
    data-page-type="form">



      <div style={{width:"100%",height:"100%",backgroundColor:"white",overflow:"auto"}}>
      <div style={{
        width: "100%", height: "7%", position: "sticky", top: "1%", backgroundColor: "white", color: "black", display: "flex",
        zIndex: 105, borderBottom: "2px solid #a91f24"
      }}>


        <div style={{ width: "40%", textAlign: "left", paddingRight: "1rem", display: "flex", alignItems: "center", fontWeight: "600" }}>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          工具栏
        </div>
        <div style={{ width: "60%", textAlign: "right", paddingRight: "1rem" }}>
          &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
          {JSON.parse(storage.pre_gyspj_item).type == "add" && <Button type="primary" onClick={handleupload}
            style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.2rem" }}>
            提交</Button>}
            {JSON.parse(storage.pre_gyspj_item).type == "view" && <Button type="primary" onClick={handleback}
            style={{ width: "6rem", height: '1.7rem', fontSize: "0.7rem", borderRadius: "5px", marginTop: "0.2rem" }}>
            返回</Button>} 
        </div>
      </div>


      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", position: "relative", width: "98%", marginLeft: "1%", backgroundColor: "", display: "flex",
          textIndent: "1rem", justifyContent: "flex-start", alignContent: "flex-start", flexWrap: "wrap"
        }}>
          {renderfileditem()}
        </div>
      </div>
      </div>
    </div>
  )
}


export default Gyspj_form
var styles = {
  maincontainer: {
    height: "100vh", backgroundColor: `white`,
    backgroundSize: "100% 100%", width: "100%", position: "absolute", left: "0", color: "white", fontSize: "0.8rem"
  },
  topcontainer: {
    width: "100%", height: "10vw", backgroundImage: "linear-gradient(to bottom,#e4e5eb , white)", paddingTop: "3vw",
    position: "relative", fontSize: "0.89rem", textIndent: "2rem", fontWeight: "800", color: "#a91f24", borderRadius: "0 0 15px 15px"
  },
  butdcstyle: { paddingLeft: "1vw", paddingRight: "1vw", height: "2vw", position: "absolute", right: "1%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
  butmainstyle: { paddingLeft: "1vw", height: "2vw", position: "absolute", right: "6.5%", top: "0%", backgroundColor: "#a91f24", fontSize: "0.8vw", borderRadius: "0.4rem", borderRadius: "0 0 0.3vw 0.3vw" },
  butbackstyle: { borderRadius: "0.4rem", backgroundColor: "#a91f24", height: "2vw", position: "absolute", right: "12%", top: "0%", fontSize: "0.8vw", borderRadius: "0 0 0.3vw 0.3vw" },
  kshcontainer: {
    width: "98%", position: "relative", backgroundColor: "white", color: "#666",
    borderRadius: "10px", paddingBottom: "2rem", overflow: "visible"
  },
}